package com.hnxxxy.oa.schedule.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hnxxxy.oa.schedule.model.NoteDO;
import com.hnxxxy.oa.schedule.mapper.NoteMapper;
import com.hnxxxy.oa.schedule.request.NoteRequest;
import com.hnxxxy.oa.schedule.service.NoteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnxxxy.oa.schedule.vo.NoteVo;
import com.hnxxxy.oa.system.constant.UserConstant;
import com.hnxxxy.oa.system.model.SysUserDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 个人便签表 服务实现类
 * </p>
 *
 * @author hzh
 * @since 2022-05-10
 */
@Slf4j
@Service
public class NoteServiceImpl extends ServiceImpl<NoteMapper, NoteDO> implements NoteService {

    @Autowired
    NoteMapper noteMapper;
    @Override
    public int insertNote(NoteRequest noteRequest) {
        SysUserDO user = (SysUserDO) StpUtil.getSession().get(UserConstant.SESSION_USER_KEY);
        NoteDO noteDO = new NoteDO();
        noteDO.setCreateTime( LocalDateTime.now());
        noteDO.setCreateBy(user.getActualName());
        int rows = noteMapper.insert(noteDO);
        return rows;
    }

    @Override
    public List<NoteVo> findAll() {
        SysUserDO user = (SysUserDO) StpUtil.getSession().get(UserConstant.SESSION_USER_KEY);
        List<NoteDO> noteDOList = noteMapper.selectList(new QueryWrapper<NoteDO>().eq("id", user.getId()));

        List<NoteVo> noteVOList = noteDOList.stream().map(obj -> {
            NoteVo noteVO = new NoteVo();
            BeanUtils.copyProperties(obj, noteVO);
            return noteVO;
        }).collect(Collectors.toList());

        log.info("全部消息:noteVOList={}",noteVOList);
        return noteVOList;
    }

    @Override
    public int deleteNote(int id) {
        SysUserDO user = (SysUserDO) StpUtil.getSession().get("userDO");
        int rows = noteMapper.delete(new QueryWrapper<NoteDO>().eq("id", id).eq("id", user.getId()));
        log.info("删除消息:rows={}",rows);
        return rows;
    }

    @Override
    public int updateNote(int id, NoteRequest noteRequest) {
        SysUserDO user = (SysUserDO) StpUtil.getSession().get(UserConstant.SESSION_USER_KEY);
        NoteDO noteDO = new NoteDO();
        BeanUtils.copyProperties(noteRequest, noteDO);
        int rows = noteMapper.update(noteDO, new QueryWrapper<NoteDO>().eq("id", id).eq("id", user.getId()));
        log.info("修改消息:rows={}",rows);
        return rows;
    }
}
